from flask_restplus import Namespace, Resource
from flask import request
from app.models import Blog,User
from flask_httpauth import HTTPTokenAuth
from app.apis.auth import auth
from app.extensions import db
from datetime import datetime


api = Namespace('blogs', description='blogs')

@api.route('/<int:bid>/','/<seach>/')
class BlogAPI(Resource):
    method_decorators = [auth.login_required]
    def get(self,seach):
        # 对于指定博客的查询
        # 包含 contains
        # users = User.query.filter(User.name.contains('un')).all()
        blog_list = []
        blog = Blog.query.filter(Blog.title.contains(seach)).all()
        for b in blog:
            blog_list.append({'博客的标题':b.title,'博客的内容':b.content,
                              '博客的作者':b.blog_user_id,
                              '博客发表的时间':str(b.create_time)})
        return {'博客':blog_list}

    # 博客的删除功能
    def delete(self, bid):
        # 根据参数找到对象的博客
        blog = Blog.query.get(bid)
        # 判断当前的博客是你的博客
        user_id = request.json.get('user_id')
        # user = User.query.filter()
        if user_id==blog.blog_user_id:
            db.session.delete(blog)
            return '博客已删除'
        return '用户错误'

@api.route('/')
class BlogList(Resource):
    # 查询所有的博客信息
    def get(self):
        blog = []
        # 查询所有的博客信息
        blog_list = Blog.query.all()
        for b in blog_list:
            # 通过博客的作者 查到作者的信息  将其添加到博客的信息中
            user = User.query.filter(b.blog_user_id==User.id).first()
            blog.append({'博客的id':b.id,'博客的标题':b.title,'博客的内容':b.content,
                         '博客的所属人':user.user_name,'博客的创建时间':str(b.create_time)})
        return {'博客列表':blog}
    def post(self):
        # 发表博客
        title = request.json.get('title')
        # 获取内容
        content = request.json.get('content')
        # 获取博客的发表者
        blog_user_id = request.json.get('blog_user_id')
        # 设置发表时间
        create_time = datetime.now()
        # 添加到数据库
        blog = Blog(title=title, content=content, blog_user_id=blog_user_id, create_time=create_time)
        # 上传
        db.session.add(blog)

        return '博客发表成功'